﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Adams.Web.Logic.Security
{
    public class Signup
    {
        public static Adams.Web.Models.Security.Signup.PageLoad PageLoad()
        {
            var model = new Adams.Web.Models.Security.Signup.PageLoad();
            return model;
        }

        public static Models.FormOutput TrySignup(Models.Security.Signup.FormInput input)
        {
            var output = Validation.PerformBasicValidation(input);

            if (!Shared.Str.IsEqual(input.Password1, input.Password2))
            {
                output.InvalidFields.Add(new Models.InvalidField() { Name = "Password2", Code = 6 });
            }

            if (output.IsValid)
            {
                var data = Data.Security.Common.GetMemberInfo(input.Email);

                if (!data.Exists)
                {
                    string passwordSalt = Shared.Encryption.GenerateSalt(16);
                    string passwordHash = Shared.Encryption.HashPassword(input.Password1, passwordSalt);

                    var save = Shared.ObjectHelper.CopyObject<Models.Security.Signup.SaveData>(input);

                    save.PasswordHash = passwordHash;
                    save.PasswordSalt = passwordSalt;

                    Data.Security.Signup.SaveMember(save);

                    string subject = "Confirm your ADAMS account, " + input.FirstName;
                    string from = Shared.Config.GetAppSetting("SecurityFromEmail");
                    string body = Logic.Email.GenerateSignupEmail(input.Email);
                    Email.QueueEmail(subject, from, input.Email, body, 1);
                }
                else
                {
                    output.InvalidFields.Add(new Models.InvalidField() { Name = "Email", Code = 21 });
                }
            }

            return output;
        }
    }
}
